package com.cs171.market.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cs171.market.Repository.OrderRepository;
import com.cs171.market.entity.CartList;
import com.cs171.market.entity.Order;
import com.cs171.market.mapper.CartListMapper;
import com.cs171.market.mapper.OrderMapper;
import com.cs171.market.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.cs171.market.entity.Order;
import com.cs171.market.entity.Script;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

/**
 * @author yangyifei
 * @version 1.0
 * @date 2020/6/20 23:31
 */

@CrossOrigin
@RestController
public class OrderController {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired(required = false)
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private CartListMapper cartListMapper;
    @Autowired(required = false)
    private UserMapper userMapper;


    /**
     * 老虎的API
     * @return
     */
    @GetMapping("orders")
    public Object getOrders(){
        JSONObject result = jsonhead();
        JSONObject dataJson = new JSONObject();
        dataJson.put("total",1);
        dataJson.put("pagenum",1);
        JSONArray oAll = (JSONArray) JSON.toJSON(orderRepository.findAll());
        dataJson.put("goods",oAll);
        result.put("data",dataJson);
        return result;
    }

    @PostMapping("payorders")
    public Object insertOrders(@RequestBody JSONObject jsonParam){
        String jsons = jsonParam.getString("items");
        String addr = jsonParam.getString("address");
        String phone = jsonParam.getString("phone");
        String dp = jsonParam.getString("deliveryPrice");
        String pp = jsonParam.getString("packPrice");
        Integer uid = jsonParam.getInteger("userId");
        JSONObject result = new JSONObject();
        Order order = new Order();
        if(jsons != null){
            System.out.println(jsons);
            JSONArray originArray = JSON.parseArray(String.valueOf(jsons));
            double price = 0.0;
            ArrayList<Script> scriptArrayList = new ArrayList<>();
            for(Object json : originArray){
                Script script = JSONObject.parseObject(json.toString(), Script.class);
                scriptArrayList.add(script);
                System.out.println(script);

            }

            for(Script s : scriptArrayList){
                price += s.getPrice() * s.getQuant();
            }
            System.out.println(dp);
            System.out.println(pp);
            order.setOprice((int) price + Integer.parseInt(dp)+Integer.parseInt(pp));
            order.setOname("itcast-59e7502d7993e");
            order.setOpay(1);
            order.setOsend("运输中");
            order.setOtime(System.currentTimeMillis()/1000);
            order.setUid(uid);
            order.setDeliveryprice(dp);
            order.setPackprice(pp);
            order.setOphone(phone);
            order.setOaddr(addr);
            order.setStaffname("骑手小王");
            order.setStaffphone("18118111811");
            orderRepository.save(order);
            result.put("code",200);
            return result;
        }
        result.put("error", "可能是数据库暂时连接不上或无此订单号，请稍后再试");
        result.put("code",500);
        return result;
    }

    /**
     * 重构代码，相似的Json Head
     * @return JsonObject
     */
    private JSONObject jsonhead() {
        JSONObject pAll = new JSONObject();
        JSONObject pSuccess = new JSONObject();
        pSuccess.put("msg", "获取成功");
        pSuccess.put("status", "200");
        pAll.put("meta", pSuccess);
        return pAll;
    }

    /**
     *
     * @param id
     * @return
     */
    @GetMapping("/order/{id}")
    public Object getOrderById(@PathVariable("id")Integer id)
    {
        JSONObject outJson=new JSONObject();
        outJson.put("success","true");

        JSONObject jsonObject=new JSONObject();
        jsonObject= (JSONObject) JSON.toJSON(orderMapper.findById(id));
        System.out.println(orderMapper.findById(id).getDeliveryprice());

        jsonObject.put("updateTime","1590013673");
        jsonObject.put("nowPosition","徐汇区枫林路");
        jsonObject.put("forecastTime",10);
        jsonObject.put("commented",false);

        JSONObject jsonObject1=new JSONObject();
        jsonObject1.put("position","长宁区虹桥路");
        jsonObject.put("arriveTime","1590013673");
        JSONObject jsonObject2=new JSONObject();
        jsonObject1.put("position","徐汇区斜土路");
        jsonObject.put("arriveTime","1590013673");

        JSONArray jsonArray=new JSONArray();
        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);
        jsonObject.put("historyPosition",jsonArray);

        List<CartList> test = cartListMapper.getCartListByGid(18);
        JSONArray cartListJson=new JSONArray();
        for(CartList each:test)
        {
            cartListJson.add(each.getMessage2());
        }
        jsonObject.put("orderItem",cartListJson);

        jsonObject.put("orderer",userMapper.getUserById2(10170919).getUname());

        outJson.put("data",jsonObject);

        return outJson;
    }

    @PostMapping("/confirm")
    //确认收货
    public Object getFee(@RequestBody JSONObject jsonParam){
        String act = jsonParam.getString("action");
        Integer id = jsonParam.getInteger("id");
        JSONObject result = new JSONObject();
        Order order = orderRepository.findById(id).orElse(null);
        if(order != null){
            result.put("code",200);
            return result;
        }
        result.put("error", "xxx");
        result.put("code",500);
        return result;
    }
}
